package com.wenlin.myproduction.util;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.wenlin.myproduction.bean.Constant;
import com.wenlin.myproduction.bean.Event;
import com.wenlin.myproduction.bean.RequestBean;
import com.wenlin.myproduction.bean.SwitchEn;
import com.wenlin.myproduction.bean.User;

import org.greenrobot.eventbus.EventBus;

//用户管理
//金币管理
public class UserManage {
    static UserManage insatnce;

    User user;//用户
    int diamonds = 300;//金币
    String session = "";//token

    public static UserManage getInstance() {
        if (insatnce == null) {
            insatnce = new UserManage();
        }
        return insatnce;
    }

    //获取当前用户信息
    public User getUser() {
        if (user == null) {
            user = new User();
        }
        return user;
    }

    //设置当前用户
    public void setUser(User user) {
        this.user = user;
    }

    //清除用户
    public void clearUser() {
        RequestBean.setToken("");
        SharePreferenceUtil.getInstance().putString("user", "");
    }

    //获取当前uid
    public int getUid() {
        return user == null ? 0 : user.uid;
    }

    //获取本地账号
    public String getAccount() {
        String account = SharePreferenceUtil.getInstance().getString("account");
        return TextUtils.isEmpty(account) ? "" : account;
    }

    public void clearAccount() {
        SharePreferenceUtil.getInstance().putString("account", "");
    }

    public String getPwd() {
        String pwd = SharePreferenceUtil.getInstance().getString("pwd");
        return TextUtils.isEmpty(pwd) ? "" : pwd;
    }

    public void clearPwd() {
        SharePreferenceUtil.getInstance().putString("pwd", "");
    }

    //获取当前电话
    public String getTel() {
        return user == null || user.Tel == null ? "" : user.Tel;
    }

    //获取当前头像
    public String getHeadUrl() {
        return user == null || user.Headurl == null ? "" : user.Headurl;
    }

    //获取帮学资格次数
    public int getHelpCount() {
        return user == null ? 0 : (int) Math.floor(user.HelpCount);
    }

    //获取当前岁数
    public int getAge() {
        return user == null ? 1 : user.Age;
    }

    //获取当前用户名
    public String getUserName() {
        return user == null || user.userName == null ? "用户" + getUid() : user.userName;
    }

    //获取百分比
    public String getUserBeatRate() {
        return user == null || user.BeatRate == null ? "80%" : user.BeatRate;
    }

    //获取持续天数
    public int getUserContinueDays() {
        return user == null ? 0 : user.ContinueDays;
    }

    //获取用户Session
    public String getSession() {
        if (TextUtils.isEmpty(session)) {
            session = SharePreferenceUtil.getInstance().getString("token");
        }
        return session;
    }

    //是否超级账号
    public boolean isSuperTest() {
        return user != null && user.SuperFlag;
    }

    //是否绑定
    public boolean isBind() {
        return user != null && !TextUtils.isEmpty(user.Tel);
    }

    //设置绑定
    public void setBind(String phoneNo) {
        if (user == null) {
            return;
        }
        user.Tel = phoneNo;
        refreshUser(user);
    }

    //是否修改账号
    public boolean isAccountModify() {
        return user != null && user.AccountFlag;
    }

    //设置账号修改
    public void setAccountModify(boolean AccountFlag) {
        if (user == null) {
            return;
        }
        user.AccountFlag = AccountFlag;
        refreshUser(user);
    }

    //是否完善信息
    public boolean isCompleteInfo() {
        return user != null && user.CompleteFlag;
    }

    //是否测评
    public boolean isEvaFlag() {
        return user != null && user.EvaFlag;
    }

    //设置测评信息
    public void setEvaFlag(boolean EvaFlag) {
        if (user == null) {
            return;
        }
        user.EvaFlag = EvaFlag;
        refreshUser(user);
    }

    //获取连续打卡天数
    public int getContinuousPunch() {
        return user != null ? user.ContinuousPunch : 0;
    }

    //获取金币
    public int getDiamonds() {
        return user != null ? user.DiamondNum : 0;
    }

    //保存金币数
    public void setDiamonds(int diamonds) {
        if (Checker.notNull(user))
            user.DiamondNum = diamonds;
    }

    //获取钻石
    public int getPurpleDiamonds() {
        return user != null ? user.PurpleDiamondNum : 0;
    }

    //获取获取钻石还差连续打卡多少天
    public int getDayToTarget() {
        return user != null ? user.DayToTarget : 0;
    }

    //获取已激活多少天了
    public int getActivationLeftDays() {
        return user != null ? user.ActivationLeftDays : 0;
    }

    public int getCouponCount() {
        return user != null ? user.CouponCount : 0;
    }

    public int getPunchCoin() {
        return user != null && user.PunchCoin > 0 ? user.PunchCoin : 1500;
    }

    //获取当前等级
    public int getLevel() {
        return user == null || user.AbilityLevel == 0 ? 1 : user.AbilityLevel;
    }

    //获取当前等级
    public String getLevelName() {
        return user == null || TextUtils.isEmpty(user.LevelName) ? "1" : user.LevelName;
    }

    //获取当前等级值
    public int getLevelValue() {
        return user == null ? 0 : user.LevelValue;
    }

    /**
     * 获取当前已经学习计划数占该等级总计划数的百分比
     *
     * @return 所求
     */
    public int getLevelProgress() {
        if (user == null) return 0;
        User.StudyPlanInfoBean info = user.StudyPlanInfo;
        if (info == null) return 0;
        int studyAlready = info.StudyCount;
        int all = info.AllPlanCount;
        if (all <= 0) return 0;
        return (int) (studyAlready / (float) all * 100);
    }

    //获取激活日期
    public String getActivationTime() {
        return user != null ? user.ActivationTime : "";
    }

    public String getFormatMiniProUidStr() {
        return user != null && user.MiniProUid > 0 ? ("ID:" + user.MiniProUid) : "待激活小程序";
    }

    //返回是否需要显示小程序弹窗——即没有MiniProUid并且非ty账号
    public boolean noMiniProUidAndNotTYAccount() {
        return getFormatMiniProUidStr().contains("待激活") && !isTest7();//20201229 ty账号不弹二维码弹窗
    }

    /**
     * 获取小程序编号
     *
     * @return 所求
     */
    public int getMiniProUid() {
        return user != null && user.MiniProUid > 0 ? user.MiniProUid : 0;
    }

    //返回是否今日任务都完成了，可以抽奖了
    public boolean canTaskDraw() {
        return user != null && user.TaskDrawFlag;
    }

    /**
     * 获取分享装的配置信息
     *
     * @return 所求
     */
    public User.SharePadInfoBean getSharePadInfo() {
        return user != null ? user.SharePadInfo : null;
    }


    //登录
    public void login(User user, String session) {
        this.user = user;

        if (isSuperTest()) {//如果是超级账号 不存本地信息
            return;
        }
        setLoginInfo(user, session);
    }

    //退出登录
    public void logout() {
        this.user = null;
        setLoginInfo(this.user, "");
        EventBus.getDefault().post(new Event.LogoutEvent());
    }

    public void saveAccount(boolean isSavePwd, String pwd) {
        String account = user == null ? "" : user.account;
        LogUtils.d("保存账号：" + account);
        SharePreferenceUtil.getInstance().putString("account", account);
        SharePreferenceUtil.getInstance().putString("pwd", isSavePwd ? pwd : "");
    }

    //设置登录信息
    void setLoginInfo(User user, String session) {
        this.session = session;
        RequestBean.setToken(session);
        refreshUser(user);
    }

    //刷新用户信息保存
    public void refreshUser(User user) {
        this.user = user;
        SharePreferenceUtil.getInstance().putString("user", user == null ? "" : user.tojson());
        EventBus.getDefault().post(new Event.RefreshUserInfoEvent());//这句跟下面的那句效果一样，只是写法不同
        EventBus.getDefault().post(new TypeData<>(TypeDataNames.updateUserInfo, true));
    }

    /**
     * 用户信息保存
     */
    public void saveUser(User user) {
        this.user = user;
        SharePreferenceUtil.getInstance().putString("user", user == null ? "" : user.tojson());
    }

    //检查是否登录
    public boolean checkLogin() {
        String json = SharePreferenceUtil.getInstance().getString("user");
        if (TextUtils.isEmpty(json)) {
            return false;
        }
        User user = new Gson().fromJson(json, User.class);
        if (user == null || user.uid == 0 || isSuperTest()) {//用户空 用户为0 超级账号 为未登录过
            return false;
        }
        setUser(user);//设置当前账号
        return true;
    }

    //设置转正手机号
    public void setSwitch(String phoneNo) {
        if (user == null) {
            return;
        }
        user.Tel = phoneNo;
        refreshUser(user);
    }

    /**
     * 获取简单加密后的手机号，类似：“182****6813”
     *
     * @return 所求
     */
    public String getFormatSimpleEncryptedTel() {
        StringBuilder sb = new StringBuilder();
        String phone = getUser().Tel;
        if (Checker.hasWord(phone)) {
            for (int i = 0; i < phone.length(); i++) {
                if (i < 3 || i > 6) {
                    sb.append(phone.charAt(i));
                } else {
                    sb.append("*");
                }
            }
        }
        return sb.toString();
    }

    //设置uid
    public void setUidAndSession(SwitchEn switchEn) {
        if (user == null
                || switchEn == null) {
            return;
        }
        this.session = switchEn.Token;
        RequestBean.setToken(this.session);
        user.uid = switchEn.UserId;
        refreshUser(user);
    }

    //设置完善信息
    public void setCompleteFlag(boolean CompleteFlag) {
        if (user == null) {
            return;
        }
        user.CompleteFlag = CompleteFlag;
        refreshUser(user);
    }

    /**
     * 是否电商体验账号——后缀为tys的账号，分享装
     *
     * @return 所求
     */
    public boolean isTest30() {
        if (user == null) {
            return false;
        }
        return user.ActivationType == Constant.ACCOUNT_TYPE_TEST30;
    }

    /**
     * 是否是测试账号——后缀为ty的账号，试用装
     *
     * @return 所求
     */
    public boolean isTest7() {
        if (user == null) {
            return false;
        }
        return user.ActivationType == Constant.ACCOUNT_TYPE_TEST7;
    }

    /**
     * 是否正式账号——后缀为zs的账号，学霸装
     *
     * @return 所求
     */
    public boolean isZs() {
        if (user == null) {
            return false;
        }
        return user.ActivationType == Constant.ACCOUNT_TYPE_ZS;
    }

    /**
     * 是否是旗舰账号——后缀为yb的账号，旗舰装
     *
     * @return 所求
     */
    public boolean isYb() {
        if (user == null) {
            return false;
        }
        return user.ActivationType == Constant.ACCOUNT_TYPE_YB;
    }

    /**
     * 是否是旗舰账号——后缀为ybs的账号，旗舰装
     *
     * @return 所求
     */
    public boolean isYbs() {
        if (user == null) {
            return false;
        }
        return user.ActivationType == Constant.ACCOUNT_TYPE_YBS;
    }

    /**
     * 是否是非正式账号，这里暂时直接对正式账号取反
     *
     * @return 所求
     */
    public boolean notZsAccount() {
        return !isZs();
    }

    /**
     * 返回到期时间
     *
     * @return 所求
     */
    public String getValidTime() {
        return user != null ? user.ValidTime : "";
    }
}
